<script setup lang="ts">
import type { FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { StorageApi } from '@/apis'
import { useForm } from '@/hooks'
import * as Regexp from '@/utils/regexp'

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<StorageApi.StorageDetailResp>()

const isCreateMode = computed(() => dataId.value === '')
const title = computed(() => (isCreateMode.value ? '新增存储' : '修改存储'))

const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
  name: null,
  code: null,
  type: 2,
  accessKey: null,
  secretKey: null,
  endpoint: null,
  bucketName: null,
  domain: null,
  description: null,
  sort: 999,
  defaultStorage: 0,
  status: 1,
})
const rules: FormInstance['rules'] = {
  name: [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线，长度为2-32位' }],
  code: [{ required: true, match: Regexp.Code, message: '编码只能含有英文、数字、下划线、短横线，以字母开头，长度为2-32位' }],
  type: [{ required: true, message: '请选择类型' }],
  accessKey: [{ required: true, message: '请输入访问密钥' }],
  secretKey: [{ required: true, message: '请输入私有密钥' }],
  endpoint: [{ required: true, message: '请输入终端节点' }],
  bucketName: [{ required: true, message: '请输入桶名称' }],
}

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await StorageApi.getDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开详情
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
}

// 打开编辑
const edit = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = false
  getDataDetail()
}

// 打开新增
const create = async () => {
  dataId.value = ''
  loading.value = false
  visible.value = true
  readonly.value = false
}

// 保存
const onSave = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) {
      return false
    }
    if (isCreateMode.value) {
      await StorageApi.create(form)
      Message.success('新增成功')
    } else {
      await StorageApi.update(form, dataId.value)
      Message.success('修改成功')
    }
    emit('change')
    visible.value = false
    return true
  } catch {
    return false
  }
}

// 取消
const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

defineExpose({ open, edit, create })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="drawer"
    :title="title"
    :loading="loading"
    :footer="isCreateMode"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly>
      <a-card title="基础信息" class="section">
        <template #extra>
          <ReadonlyEditButton
            v-if="!isCreateMode"
            :readonly="readonly"
            :deleteable="false"
            @edit="onEdit"
            @cancel="onCancel"
            @save="onSave"
          />
        </template>
        <a-row :gutter="28">
          <readonly-form-item label="名称" field="name" :span="24">
            <a-input v-model.trim="form.name" placeholder="请输入名称" />
          </readonly-form-item>
          <readonly-form-item label="类型" field="type" :span="12">
            <DictSelect v-model.trim="form.type" code="StorageTypeEnum" :disabled="!isCreateMode" type="button" />
          </readonly-form-item>
          <readonly-form-item label="编码" field="code" :span="12">
            <a-input v-model.trim="form.code" placeholder="请输入编码" />
          </readonly-form-item>
          <readonly-form-item label="桶名称" field="bucketName" :span="12">
            <a-input v-model.trim="form.bucketName" placeholder="请输入桶名称" />
          </readonly-form-item>
          <readonly-form-item label="域名" field="domain" :span="12">
            <a-input v-model.trim="form.domain" placeholder="请输入域名" />
          </readonly-form-item>
          <readonly-form-item label="描述" field="description" :span="24">
            <a-textarea v-model.trim="form.description" placeholder="请输入描述" :max-length="255" show-word-limit />
          </readonly-form-item>
          <readonly-form-item label="默认存储" field="defaultStorage" :span="8">
            <DictSelect v-model="form.defaultStorage" type="boolean" code="BooleanEnum" />
          </readonly-form-item>
          <readonly-form-item label="状态" field="status" :span="8">
            <DictSelect v-model="form.status" type="status" code="CommonStatusEnum" />
            <template #readonly>
              <CellStatus :status="dataDetail?.status" />
            </template>
          </readonly-form-item>
          <readonly-form-item label="排序号" field="sort" :span="8">
            <a-input-number v-model="form.sort" placeholder="请输入排序" :min="1" mode="button" />
          </readonly-form-item>
        </a-row>
      </a-card>
      <a-card v-if="form.type === 1" title="对象存储信息" class="section">
        <readonly-form-item label="访问密钥" field="accessKey" :span="24">
          <a-input v-model.trim="form.accessKey" placeholder="请输入Access Key(访问密钥)" :max-length="255" show-word-limit />
        </readonly-form-item>
        <readonly-form-item label="私有密钥" field="secretKey" :span="24">
          <a-input v-model.trim="form.secretKey" placeholder="请输入Secret Key(私有密钥)" :max-length="255" show-word-limit />
        </readonly-form-item>
        <readonly-form-item label="终端节点" field="endpoint" :span="24">
          <a-input v-model.trim="form.endpoint" placeholder="请输入Endpoint(终端节点)" :max-length="255" show-word-limit />
        </readonly-form-item>
      </a-card>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped></style>
